//
//  CartoonDetailsViewController.m
//  Cartoon
//
//  Created by dllo on 15/10/31.
//  Copyright © 2015年 YSZ. All rights reserved.
//

#import "CartoonDetailsViewController.h"
#import "CartoonDetailsBigTableViewCell.h"
#import "StarView.h"
#import "CartoonDetailsModel.h"
#import "CartoonDetailsCommentModel.h"
#import "CartoonReadingViewController.h"
#import "CartoonDownLoadViewController.h"
#import "AlreadyReading.h"
#import "CartoonDetailsCollectionViewCell.h"
#import "UMSocial.h"
@interface CartoonDetailsViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,UICollectionViewDelegate,UMSocialUIDelegate>
@property (nonatomic, strong) UITableView *bigTableView;
@property (nonatomic, strong) UIButton *continueLookButton;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *readingArr;
@property (nonatomic, strong) FMDatabase *db;
@property (nonatomic,retain)UIBarButtonItem *cameraItem;
@property (nonatomic, strong) NSMutableArray *nameArray;
@end

@implementation CartoonDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIBarButtonItem *shareItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"分享1.png"] style:UIBarButtonItemStylePlain target:self action:@selector(share:)];
    self.cameraItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"收藏.png"] style:UIBarButtonItemStylePlain target:self action:@selector(cameraItem:)];
    
    NSArray *itemsArr = @[shareItem,_cameraItem];
    shareItem.tintColor =  [UIColor whiteColor];
    _cameraItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItems = itemsArr;
    [self setBBBBB];
    [self handler];
    
}

- (void)setBBBBB
{
    
    NSString *dbPath = [NSString stringWithFormat:@"%@/Documents/1.rdb",NSHomeDirectory()];
    
    NSLog(@"%@......",dbPath);
    
    self.db = [FMDatabase databaseWithPath:dbPath];
    
    
    BOOL result = [self.db open];
    if (result == NO) {
        NSLog(@"%d666",result);
    }else{
        
        BOOL creatResult = [self.db executeUpdate:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS Cartoon (id integer , name text NOT NULL,idd integer PRIMARY KEY AUTOINCREMENT, title text NOT NULL, pic text NOT NULL , gx text NOT NULL, star integer NOT NULL)"]];
        
        NSLog(@"创建0000000是否成功 :%d",creatResult);
    }
    
}
- (void)share:(UIBarButtonItem *)btg
{
    
    CartoonDetailsModel *detail = [_dataArr objectAtIndex:0];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:detail.cover_url]];
    UIImage *image = [UIImage imageWithData:data];
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"563c0ed2e0f55abb80002eab" shareText:detail.title shareImage: image
        shareToSnsNames:[NSArray arrayWithObjects:UMShareToWechatTimeline,UMShareToSina,UMShareToQQ,UMShareToWechatSession,UMShareToQzone, nil] delegate:self];
    
    

}

-(void)didSelectSocialPlatform:(NSString *)platformName withSocialData:(UMSocialData *)socialData
{
 
    if (platformName == UMShareToSina) {
        socialData.shareText = @"分享到新浪微博的文字内容";
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
        
        snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
            
            //          获取微博用户名、uid、token等
            
            if (response.responseCode == UMSResponseCodeSuccess) {
                
                UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
                
                NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
                
            }});
        
        [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToSina  completion:^(UMSocialResponseEntity *response){
            NSLog(@"SnsInformation is %@",response.data);
        }];
        
        
        
    }
    else if(platformName == UMShareToQQ)
    
    {
        
[UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeImage;
        
    socialData.shareText = @"分享到QQ的文字内容";
       
       // 获取accestoken以及QQ用户信息，得到的数据在回调Block对象形参respone的data属性
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
        
        snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
            
            //          获取微博用户名、uid、token等
            
            if (response.responseCode == UMSResponseCodeSuccess) {
                
                UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToQQ];
                
                NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
                
            }});
        [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToQQ  completion:^(UMSocialResponseEntity *response){
            NSLog(@"SnsInformation is %@",response.data);
        }];
    }
    
    else if (platformName == UMShareToQzone)
    {
        socialData.shareText = @"分享到QQ空间的文字内容";
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQzone];
        
        snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
            
            //          获取微博用户名、uid、token等
            
            if (response.responseCode == UMSResponseCodeSuccess) {
                
                UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToQzone];
                
                NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
                
            }});
        [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToQzone  completion:^(UMSocialResponseEntity *response){
            NSLog(@"SnsInformation is %@",response.data);
        }];
        

    
    }else if(platformName == UMShareToWechatSession)
    {
        [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeApp;        socialData.shareText = @"分享到微信的文字内容";
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
        
        snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
            
            if (response.responseCode == UMSResponseCodeSuccess) {
                
                UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary]valueForKey:UMShareToWechatSession];
                
                NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
                
            }
            
        });
        [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToWechatSession  completion:^(UMSocialResponseEntity *response){
            NSLog(@"SnsInformation is %@",response.data);
        }];
        
        
    }
    
}


-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}

-(BOOL)isDirectShareInIconActionSheet
{
    return YES;
}

- (void)cameraItem:(UIBarButtonItem *)btg
{
    
    CartoonDetailsModel *detail = [_dataArr objectAtIndex:0];
    
    FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM Cartoon"];
    // 2.遍历结果
    
    self.nameArray = [NSMutableArray array];
    while ([resultSet next]) {
        NSString *num = [resultSet stringForColumn:@"idd"];
        [self.nameArray addObject:num];
    }
    if ([self.nameArray containsObject:detail.comic_id]) {
        
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"已经收藏" message:@"我已经在收藏列表了呦😊" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道啦" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }
    else{
        BOOL re = [self.db executeUpdate:@"INSERT INTO Cartoon (name, idd, title ,pic , gx , star) VALUES (?, ?, ?, ?, ?, ?)", detail.artist_name, detail.comic_id ,detail.title,detail.cover_url,detail.lastup ,detail.grade];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"收藏成功" message:@"要常来收藏列表看我呦😊" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道啦" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"////%d",re);
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
    NSLog(@"保存");
}



- (void)handler
{
    NSString *str = [NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comic/comicDetailForIosV2/uin/0/local_version/3.1.0/channel/1001/guest_id/491A80FA-091B-4330-B939-7DE39BB24F7F/comic_id/%@",self.idtext];
    [NetHandler dataWithUrl:str complant:^(id data) {
        NSDictionary *bigDic = [NSDictionary dictionaryWithDictionary:data];
        CartoonDetailsModel *detail = [[CartoonDetailsModel alloc] init];
        [detail setValuesForKeysWithDictionary:[[bigDic objectForKey:@"data"] objectForKey:@"comic"]];
        self.dataArr = [NSMutableArray arrayWithObject:detail];
        
        
        self.bigTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SelfViewWidth, SelfViewHeight - 64 - 49) style:UITableViewStylePlain];
        _bigTableView.delegate = self;
        _bigTableView.dataSource = self;
        [_bigTableView registerClass:[CartoonDetailsBigTableViewCell class] forCellReuseIdentifier:@"big"];
        [self.view addSubview:_bigTableView];
        self.bigTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _bigTableView.frame.size.width, _bigTableView.frame.size.height / 3 + (40 + 40) * HEIGHT)];

        // 毛玻璃效果
        UIImageView *imageViewEff = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SelfViewWidth, SelfViewHeight /3-30)];
        [imageViewEff sd_setImageWithURL:[NSURL URLWithString:detail.cover_url] placeholderImage:[UIImage imageNamed:@"5"]];
        [self.bigTableView.tableHeaderView addSubview:imageViewEff];
        UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        UIVisualEffectView *viewEff = [[UIVisualEffectView alloc] initWithEffect:blur];
        viewEff.frame = CGRectMake(0, 0, SelfViewWidth, SelfViewHeight /3-30);
        [imageViewEff addSubview:viewEff];

        
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20 * WIDTH, 20 * HEIGHT, _bigTableView.frame.size.width / 3 * WIDTH,( _bigTableView.frame.size.height / 3 - 20  * HEIGHT))];
        imageView.tag = 1010;
        [imageView sd_setImageWithURL:[NSURL URLWithString:detail.cover_url] placeholderImage:[UIImage imageNamed:@"5"]];
        [self.bigTableView.tableHeaderView addSubview:imageView];
        
        
        UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(imageView.frame.size.width + 40 * WIDTH, 40  * HEIGHT, imageView.frame.size.width / 3 , imageView.frame.size.width / 3 - (10 + 10) * HEIGHT)];
        UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(imageView.frame.size.width + 40 * WIDTH + label1.frame.size.width + 10 * WIDTH, 40 * HEIGHT, imageView.frame.size.width / 3 ,imageView.frame.size.width / 3 - (10 + 10) * HEIGHT)];
        UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(imageView.frame.size.width + 40 * WIDTH + 2 * (label1.frame.size.width + 10 * WIDTH) , 40 * HEIGHT, imageView.frame.size.width / 3 , imageView.frame.size.width / 3 - (10 + 10)* HEIGHT)];
        NSArray *typeArray = [detail.type componentsSeparatedByString:@" "];
        
        if (typeArray.count > 0) {
            label1.text = [typeArray objectAtIndex:0];
            label2.hidden = YES;
            label3.hidden = YES;
        }else if (typeArray.count > 1) {
            label1.text = [typeArray objectAtIndex:0];
            label2.text = [typeArray objectAtIndex:1];
            label3.hidden = YES;
        }else{
            label1.text = [typeArray objectAtIndex:0];
            label2.text = [typeArray objectAtIndex:1];
            label3.text = [typeArray objectAtIndex:2];
        }
        

        label1.backgroundColor = [UIColor orangeColor];
        label2.backgroundColor = [UIColor yellowColor];
        label3.backgroundColor = [UIColor greenColor];
        label1.textAlignment = NSTextAlignmentCenter;
        label2.textAlignment = NSTextAlignmentCenter;
        label3.textAlignment = NSTextAlignmentCenter;
        label1.layer.cornerRadius = label1.frame.size.height / 4;
        label2.layer.cornerRadius = label2.frame.size.height / 4;
        label3.layer.cornerRadius = label3.frame.size.height / 4;
        label1.font = [UIFont systemFontOfSize:imageView.frame.size.width / 3  * WIDTH / 2];
        label2.font = [UIFont systemFontOfSize:imageView.frame.size.width / 3  * WIDTH / 2];
        label3.font = [UIFont systemFontOfSize:imageView.frame.size.width / 3  * WIDTH / 2];
        label1.clipsToBounds = YES;
        label2.clipsToBounds = YES;
        label3.clipsToBounds = YES;
        [self.bigTableView.tableHeaderView addSubview:label1];
        [self.bigTableView.tableHeaderView addSubview:label2];
        [self.bigTableView.tableHeaderView addSubview:label3];
        
        
        
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(label1.frame.origin.x , label1.frame.origin.y + 35 *HEIGHT  , (SelfViewWidth / 3 * 2 - 40) * WIDTH, 20 * HEIGHT)];
        nameLabel.text = detail.title;
        nameLabel.tag = 1007;
        nameLabel.font = [UIFont systemFontOfSize:22 * WIDTH];
        [self.bigTableView.tableHeaderView addSubview:nameLabel];
        
        
        
        UILabel *authorLabel = [[UILabel alloc] initWithFrame:CGRectMake(label1.frame.origin.x, label1.frame.origin.y + 70 * HEIGHT, SelfViewWidth / 3 * 2 * WIDTH, 20 * HEIGHT)];
        authorLabel.text = detail.artist_name;
        authorLabel.font = [UIFont systemFontOfSize:15 * WIDTH];
        [self.bigTableView.tableHeaderView addSubview:authorLabel];
        
        
        StarView *starView = [[StarView alloc] initWithFrame:CGRectMake(authorLabel.frame.origin.x , authorLabel.frame.origin.y + 30 * HEIGHT, 80 * WIDTH, 20 * HEIGHT)];
        starView.starNum = [detail.grade integerValue];
        [self.bigTableView.tableHeaderView addSubview:starView];
        UILabel *starLabel = [[UILabel alloc] initWithFrame:CGRectMake(starView.frame.origin.x + starView.frame.size.width + 10 * HEIGHT,authorLabel.frame.origin.y + 30 * HEIGHT, 40 * WIDTH, 20 * HEIGHT)];
        starLabel.text = detail.grade_ave;
        [self.bigTableView.tableHeaderView addSubview:starLabel];

        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"YYYY-MM-dd HH:mm"];
        NSString *timestamp = [formatter stringFromDate:[NSDate date]];
        if ([timestamp isEqualToString:@"2015-11-22 19:12"]) {
        
        UIButton *downLoadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        downLoadButton.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:69 / 255.0 blue:0 / 255.0 alpha:1];
        downLoadButton.frame = CGRectMake(30 * WIDTH, imageView.frame.origin.y + imageView.frame.size.height + 10 * HEIGHT, SelfViewWidth / 2 - 45 * WIDTH, 30 *HEIGHT);
        [downLoadButton setTitle:@"下载" forState:UIControlStateNormal];
        downLoadButton.titleLabel.font = [UIFont systemFontOfSize:20* WIDTH];
        downLoadButton.tintColor = [UIColor whiteColor];
        [downLoadButton addTarget:self action:@selector(downLoadButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.bigTableView.tableHeaderView addSubview:downLoadButton];
        }
        
        
        UIButton *readButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        readButton.backgroundColor = [UIColor colorWithRed:0 / 255.0 green:255 / 255.0 blue:255 / 255.0 alpha:1];
        if ([timestamp isEqualToString:@"2015-11-22 19:12"]) {
        readButton.frame = CGRectMake(60 * WIDTH + SelfViewWidth / 2 - 45 * WIDTH , imageView.frame.origin.y + imageView.frame.size.height + 10 * HEIGHT, SelfViewWidth / 2 - 45 * WIDTH, 30 *HEIGHT);
        }else{
        readButton.frame = CGRectMake(40, imageView.frame.origin.y + imageView.frame.size.height + 10 * HEIGHT, SelfViewWidth - 80, 30 *HEIGHT);
        }
        [readButton setTitle:@"续读" forState:UIControlStateNormal];
        readButton.titleLabel.font = [UIFont systemFontOfSize:20 * WIDTH];
        readButton.tintColor = [UIColor whiteColor];
        [readButton addTarget:self action:@selector(readButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.bigTableView.tableHeaderView addSubview:readButton];
        
        
        
        UIButton *detailsButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [detailsButton setTitle:@"详情" forState:UIControlStateNormal];
        detailsButton.frame = CGRectMake(0, self.bigTableView.tableHeaderView.frame.size.height - 40 * HEIGHT, SelfViewWidth / 3 * WIDTH, 40 * HEIGHT);
        detailsButton.tintColor = [UIColor orangeColor];
        [detailsButton addTarget:self action:@selector(detailsButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        detailsButton.tag = 1001;
        [self.bigTableView.tableHeaderView addSubview:detailsButton];
        
        UIButton *catalogueButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [catalogueButton setTitle:@"目录" forState:UIControlStateNormal];
        catalogueButton.frame = CGRectMake(SelfViewWidth / 3, self.bigTableView.tableHeaderView.frame.size.height - 40 * HEIGHT, SelfViewWidth / 3 * WIDTH, 40 * HEIGHT);
        [catalogueButton addTarget:self action:@selector(catalogueButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        catalogueButton.tag = 1002;
        [self.bigTableView.tableHeaderView addSubview:catalogueButton];
        
        UIButton *commentButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [commentButton setTitle:@"评论" forState:UIControlStateNormal];
        commentButton.frame = CGRectMake(SelfViewWidth / 3 * 2, self.bigTableView.tableHeaderView.frame.size.height - 40 * HEIGHT, SelfViewWidth / 3 * WIDTH, 40 * HEIGHT);
        [commentButton addTarget:self action:@selector(commentButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        commentButton.tag = 1003;
        [self.bigTableView.tableHeaderView addSubview:commentButton];
        
        _bigTableView.allowsSelection = NO;

        
        
    }];
    
}
- (void)detailsButtonAction:(UIButton *)btn
{
    [self.bigTableView.tableHeaderView viewWithTag:1002].tintColor = nil;
    [self.bigTableView.tableHeaderView viewWithTag:1003].tintColor = nil;
    btn.tintColor = [UIColor orangeColor];
    CartoonDetailsBigTableViewCell *cell = [self.bigTableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
    cell.myScrollView.contentOffset = CGPointMake(0, 0);
}
- (void)catalogueButtonAction:(UIButton *)btn
{
    [self.bigTableView.tableHeaderView viewWithTag:1001].tintColor = nil;
    [self.bigTableView.tableHeaderView viewWithTag:1003].tintColor = nil;
    btn.tintColor = [UIColor orangeColor];
    CartoonDetailsBigTableViewCell *cell = [self.bigTableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
    cell.myScrollView.contentOffset = CGPointMake(SelfViewWidth, 0);
}
- (void)commentButtonAction:(UIButton *)btn
{
    [self.bigTableView.tableHeaderView viewWithTag:1001].tintColor = nil;
    [self.bigTableView.tableHeaderView viewWithTag:1002].tintColor = nil;
    btn.tintColor = [UIColor orangeColor];
    CartoonDetailsBigTableViewCell *cell = [self.bigTableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
    cell.myScrollView.contentOffset = CGPointMake(SelfViewWidth * 2, 0);
}

- (void)readButtonAction:(UIButton *)btn
{
    BOOL result = [[FMDB shareFMDB].db open];
    
    if (result == NO) {
        NSLog(@"NO == %d",result);
        
    }else{
        
        BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table AlreadyReading (cartoonID text primary key, cartoonPage text)"]];
        
        NSLog(@"创建是否成功 :%d",creatResult);
        
    }
    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM AlreadyReading"];
    NSMutableArray *array = [NSMutableArray array];
    CartoonDetailsModel *model = [self.dataArr objectAtIndex:0];
    while ([set next]) {
        
        AlreadyReading *read = [[AlreadyReading alloc]init];
        read.cartoonID = [set stringForColumn:@"cartoonID"];
        read.cartoonPage = [set stringForColumn:@"cartoonPage"];
        if ([[[read.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:model.comic_id]) {
            [array addObject:read];
            break;
        }
    }
    if (array.count > 0) {
       AlreadyReading *read = array[0];
        CartoonReadingViewController *reading = [[CartoonReadingViewController alloc] init];
        
        reading.page = [model.lated_seqno integerValue] - [[[read.cartoonID componentsSeparatedByString:@"/"] firstObject] integerValue];
        reading.comic_id = model.comic_id;
        reading.cover_url = model.cover_url;
        reading.bigTitle = model.title;
        reading.lated_seqno = model.lated_seqno;
        [self.navigationController pushViewController:reading animated:YES];
        
    }
    

}
- (void)downLoadButtonAction:(UIButton *)btn
{
    CartoonDownLoadViewController *downLoad = [[CartoonDownLoadViewController alloc] init];
    downLoad.model = [self.dataArr lastObject];
    downLoad.dataArr = self.dataArr;
    CartoonDetailsModel *detail = [self.dataArr lastObject];
    downLoad.myImageUrl = detail.cover_url;
    
    UIImageView *imageView = (UIImageView *)[self.bigTableView.tableHeaderView viewWithTag:1010];
    downLoad.myImage = imageView.image;
    UILabel *name = (UILabel *)[self.bigTableView.tableHeaderView viewWithTag:1007];
    downLoad.name = name.text;
    [self.navigationController pushViewController:downLoad animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.bigTableView.frame.size.height - self.bigTableView.tableHeaderView.frame.size.height;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CartoonDetailsBigTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"big"];
    cell.model = [self.dataArr objectAtIndex:0];
    NSLog(@"%@",cell.model.comic_id);
    cell.myScrollViewDelegate = self;
    cell.myCollectionDelegate = self;
    return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([[self.bigTableView.tableHeaderView viewWithTag:1001].tintColor isEqual:[UIColor orangeColor]]) {
        if ([scrollView isKindOfClass:[UITableView class]] && scrollView.frame.origin.x == 0) {
            if(scrollView.contentOffset.y > 0){
                if (self.bigTableView.frame.size.height < SelfViewHeight - 49 - 64 + self.bigTableView.tableHeaderView.frame.size.height - 40) {
                    self.bigTableView.frame = CGRectMake(0, - self.bigTableView.tableHeaderView.frame.size.height + 40 * HEIGHT + 64, SelfViewWidth, SelfViewHeight - 49 - 64 + self.bigTableView.tableHeaderView.frame.size.height - 40 * HEIGHT);
                    [self.bigTableView reloadData];
                }
            }else if(scrollView.contentOffset.y < 0){
                if (self.bigTableView.frame.size.height > SelfViewHeight - 64 - 49) {
                    self.bigTableView.frame = CGRectMake(0, 64, SelfViewWidth, SelfViewHeight - 64 - 49);
                }
            }
        }
    };
    if ([[self.bigTableView.tableHeaderView viewWithTag:1002].tintColor isEqual:[UIColor orangeColor]]) {
        if ([scrollView isKindOfClass:[UICollectionView class]]) {
            
            if(scrollView.contentOffset.y > - 40 * HEIGHT){

                if (self.bigTableView.frame.size.height < SelfViewHeight - 49 - 64 + self.bigTableView.tableHeaderView.frame.size.height - 40 * HEIGHT) {
                    self.bigTableView.frame = CGRectMake(0, - self.bigTableView.tableHeaderView.frame.size.height + 40 * HEIGHT + 64, SelfViewWidth, SelfViewHeight - 49 - 64 + self.bigTableView.tableHeaderView.frame.size.height - 40 * HEIGHT);
                    [self.bigTableView reloadData];
                }
            }else if(scrollView.contentOffset.y < -40 * HEIGHT){
                if (self.bigTableView.frame.size.height > SelfViewHeight - 64 - 49) {
                    self.bigTableView.frame = CGRectMake(0, 64, SelfViewWidth, SelfViewHeight - 64 - 49);
                }
            }
        }else{
            if (scrollView.contentOffset.y < 0) {
                if (self.bigTableView.frame.size.height > SelfViewHeight - 64 - 49) {
                    self.bigTableView.frame = CGRectMake(0, 64, SelfViewWidth, SelfViewHeight - 64 - 49);
                    [self.bigTableView reloadData];
//                    NSLog(@"???");
                }else if (scrollView.contentOffset.y > 0){
                    self.bigTableView.frame = CGRectMake(0, - self.bigTableView.tableHeaderView.frame.size.height + 40 * HEIGHT + 64, SelfViewWidth, SelfViewHeight - 49 - 64 + self.bigTableView.tableHeaderView.frame.size.height - 40 * HEIGHT);
                    [self.bigTableView reloadData];
//                    NSLog(@"!!!");
                }
            }
        }
    };
    if ([[self.bigTableView.tableHeaderView viewWithTag:1003].tintColor isEqual:[UIColor orangeColor]]) {
        if ([scrollView isKindOfClass:[UITableView class]] && scrollView.frame.origin.x == SelfViewWidth * 2) {
            if(scrollView.contentOffset.y > 0){
                if (self.bigTableView.frame.size.height < SelfViewHeight - 49 - 64 + self.bigTableView.tableHeaderView.frame.size.height - 40 * HEIGHT) {
                    self.bigTableView.frame = CGRectMake(0, - self.bigTableView.tableHeaderView.frame.size.height + 40 * HEIGHT + 64, SelfViewWidth, SelfViewHeight - 49 - 64 + self.bigTableView.tableHeaderView.frame.size.height - 40 * HEIGHT);
                    [self.bigTableView reloadData];
                }
            }else if(scrollView.contentOffset.y < 0){
                if (self.bigTableView.frame.size.height > SelfViewHeight - 64 - 49) {
                    self.bigTableView.frame = CGRectMake(0, 64, SelfViewWidth, SelfViewHeight - 64 - 49);
                }
            }
        }
    };
    if ([scrollView isKindOfClass:[UITableView class]] || [scrollView isKindOfClass:[UICollectionView class]]) {

    }else{
        NSInteger x = scrollView.contentOffset.x / SelfViewWidth;
    if (x == 0) {
        [self.bigTableView.tableHeaderView viewWithTag:1002].tintColor = nil;
        [self.bigTableView.tableHeaderView viewWithTag:1003].tintColor = nil;
        [self.bigTableView.tableHeaderView viewWithTag:1001].tintColor = [UIColor orangeColor];
    }else if (x == 1){
        [self.bigTableView.tableHeaderView viewWithTag:1001].tintColor = nil;
        [self.bigTableView.tableHeaderView viewWithTag:1003].tintColor = nil;
        [self.bigTableView.tableHeaderView viewWithTag:1002].tintColor = [UIColor orangeColor];
    }else{
        [self.bigTableView.tableHeaderView viewWithTag:1001].tintColor = nil;
        [self.bigTableView.tableHeaderView viewWithTag:1002].tintColor = nil;
        [self.bigTableView.tableHeaderView viewWithTag:1003].tintColor = [UIColor orangeColor];
    }
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    BOOL result = [[FMDB shareFMDB].db open];
    
    if (result == NO) {
        NSLog(@"NO == %d",result);
        
    }else{
        
        BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table AlreadyReading (cartoonID text primary key, cartoonPage text)"]];
        
        NSLog(@"创建是否成功 :%d",creatResult);
        
    }
    
    CartoonReadingViewController *reading = [[CartoonReadingViewController alloc] init];
    reading.page = indexPath.item;
    CartoonDetailsModel *model = [self.dataArr objectAtIndex:0];
    reading.comic_id = model.comic_id;
    reading.cover_url = model.cover_url;
    reading.bigTitle = model.title;
    reading.lated_seqno = model.lated_seqno;

    
    
    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM AlreadyReading"];
    NSMutableArray *array = [NSMutableArray array];
    
    while ([set next]) {
        
        AlreadyReading *read = [[AlreadyReading alloc]init];
        read.cartoonID = [set stringForColumn:@"cartoonID"];
        read.cartoonPage = [set stringForColumn:@"cartoonPage"];
        if ([[[read.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:model.comic_id]) {
            [array addObject:read];
            break;
        }
    }
    
    if (array.count > 0) {
        AlreadyReading *read = array[0];
        if ([model.lated_seqno integerValue] - indexPath.item == [[[read.cartoonID componentsSeparatedByString:@"/"] firstObject] integerValue]) {
            [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update AlreadyReading set cartoonID = '%@' where cartoonID = '%@' and cartoonPage = '%@'",[NSString stringWithFormat:@"%ld/%@",[model.lated_seqno integerValue] - indexPath.item,model.comic_id],read.cartoonID,read.cartoonPage]];
        }else{
            [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update AlreadyReading set cartoonID = '%@' where cartoonID = '%@' and cartoonPage = '%@'",[NSString stringWithFormat:@"%ld/%@",[model.lated_seqno integerValue] - indexPath.item,model.comic_id],read.cartoonID,read.cartoonPage]];
            [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update AlreadyReading set cartoonPage = '%@' where cartoonID = '%@' and cartoonPage = '%@'",@"1",[NSString stringWithFormat:@"%ld/%@",[model.lated_seqno integerValue] - indexPath.item,model.comic_id],read.cartoonPage]];
        }
        
    }else{
    NSLog(@"%@",[NSString stringWithFormat:@"%@/%@",[NSString stringWithFormat:@"%ld",[model.lated_seqno integerValue] - indexPath.item],model.comic_id]);
    BOOL insertResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"insert into AlreadyReading values ('%@','%@')",[NSString stringWithFormat:@"%@/%@",[NSString stringWithFormat:@"%ld",[model.lated_seqno integerValue] - indexPath.item],model.comic_id],@"1"]];
    if (insertResult == YES) {
        NSLog(@"插入成功");
    }else{
        NSLog(@"插入失败");
    }
    }

    

    

    [self.navigationController pushViewController:reading animated:YES];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    NSIndexPath *index = [NSIndexPath indexPathForItem:0 inSection:0];
    CartoonDetailsBigTableViewCell *cell = [self.bigTableView cellForRowAtIndexPath:index];
    cell.FMDBarray = nil;
    [cell.myCollectionView reloadData];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
